/*从代客下单跳转的*/
/*if(sessionStorage.getItem("orderId")){
    $("#orderCode").val(sessionStorage.getItem("orderId"));
    sessionStorage.removeItem("orderId");
    getList();
}*/
/*获取收货地址*/
discountdata(123)
function discountdata (val) {
    if(val==123){
        //初始化 省
        var user_data = {
            level: '101',
            // memberId:'10258',
        }
        var succCallBack = function (data, status, response) {
            console.log(data)
            if(data.errorCode=="0"){
                var tab_data=data.list;
                if(tab_data==''){
                    cer+='<option value=""></option>'
                    $("#getArea").html(cer);
                }else{
                    var cer="<option value=''>请选择收货区域</option>"
                    for(var i=0; i<tab_data.length; i++){
                        cer+='<option value="'+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                    }
                    $("#getArea").html(cer);
                }
            }
        };
        web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);
    }else if(val==1){
        //市
        var special=$('#getArea').val()
        if(special==""){
            var cer="<option value=''>请选择收货位置</option>"
            $("#getPlace").html(cer);
        }else {
            var user_data = {
                level: '102',
                // memberId:'10258',
                parentCode:special
            }
            var succCallBack = function (data, status, response) {
                if(data.errorCode=="0"){
                    var tab_data=data.list;
                    if(tab_data==''){
                        cer+='<option value=""></option>'
                        $("#getPlace").html(cer);
                    }else{
                        var cer="<option value=''>请选择收货位置</option>"
                        for(var i=0; i<tab_data.length; i++){
                            cer+='<option value="'+tab_data[i].code+'">'+tab_data[i].name+'</option>'
                        }
                        $("#getPlace").html(cer);
                    }
                }
            };
            web.doAjax(root.member.getLowerAddress,'post',user_data, succCallBack);
        }
    }
}
/*表格渲染*/
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];

function orderList(data) {
    dataSource.splice(0, dataSource.length);//清空数组
    if (data.data != null) {
        var datashu = data.data.startIndex + 1;
        $.each(data.data.result, function (i, field) {
            var datashus = datashu++
            var rowData = new Array();
            rowData.push(field.order_id);
            rowData.push(field.created_at);
            rowData.push(field.customer_name);
            rowData.push(field.listAddressReceiver[0]);
            rowData.push(field.paid_type);
            rowData.push(field.paid_amount);
            rowData.push(field.order_status);
            rowData.push(field.received_phone);
            rowData.push(field.source);
            rowData.push(field.used_total_points);
            rowData.push(datashus);
            rowData.push(field.products);//商品信息
            dataSource.push(rowData);
        });
    }

    initDataTable(dataSource);
}
var paidtypeall={
    '1001': "在线支付", '1002': "支付宝支付", '1003': "微信支付", '1101': "货到付款", '1102': "货到付款-现金", '1103': "货到付款-pos机", '1201': "账期支付",
    '1301': "银行转账", '1401': "银行汇票", '1601': "积分支付", '1701': "门店付款"
}
var sourceall={
'10': "Android", '20': "IOS", '30': "wap", '40': "PC", '50': "代客下单", '60': "代客下单（综合）", '70': "门店触摸屏",
}
function initDataTable(dataSource) {
    var outHtml = '';
    for(var i=0;i<dataSource.length;i++){
        var curData= dataSource[i];

        var inquiryStr = '';
        var productData = curData[11];
        var productStr = '';
        var curProLen = productData ? productData.length : 1;

        var receivernames=""
        if (curData[3]==undefined || curData[3]==null){
            receivernames=""
        }else{
            receivernames=curData[3].receiver_name
        }
        var state = "";
        switch (curData[6]) {
            case 9:
                $("#affirmMoney").css({
                    display: "inline"
                });
                state = "待付款";
                break;
            case 10:
                $("#affirmMoney").css({
                    display: "inline"
                });
                state = "待付款";
                break;
            case 20:
                $("#detailCancel").css({
                    display: "inline"
                });
                $("#pass").css({
                    display: "inline"
                });
                state = "待审核";
                break;
            case 30:
                $("#detailCancel").css({
                    display: "inline"
                });
                state = "待配货";
                break;
            case 40:
                $("#detailCancel").css({
                    display: "inline"
                });
                state = "待出库";
                break;
            case 50:
                $("#detailCancel").css({
                    display: "inline"
                });
                state = "待发货";
                break;
            case 60:
                $("#clientRejection").css({
                    display: "inline"
                });
                state = "待收货";
                break;
            case 70:
                $("#returnGoods").css({
                    display: "inline"
                });
                $("#maintain").css({
                    display: "inline"
                });
                $("#affirmMoney").css({
                    display: "inline"
                });
                state = "已收货，待结算";
                break;
            case 80:
                $("#returnGoods").css({
                    display: "inline"
                });
                $("#maintain").css({
                    display: "inline"
                });
                state = "订单成功";
                break;
            case 90:
                $("#returnGoods").css({
                    display: "inline"
                });
                $("#maintain").css({
                    display: "inline"
                });
                state = "交易完成";
                break;
            case 100:
                $("#buyAgain").css({
                    display: "inline"
                });
                $("#cancleReason").css({
                    display: "inline"
                });
                state = "已取消";
                break;
            case 110:
                $("#returnReason").css({
                    display: "inline"
                });
                state = "交易关闭";
                break;
        }
        var valall=""
        if(curData[9]==0 || curData[9]==null  ||curData[9]==""){
            if (curData[6]!=9&&curData[6]!=10&&curData[6]!=20){
                valall= '<span class="powerButton 109"><a onclick="orderchange(\'改价详情\',\'changePriceDetails.html\',\''+curData[0]+'\',1)">改价详情</a></span>';
            }else{
                valall = '<span class="powerButton 109"><a onclick="orderchange(\'修改价格\',\'changePriceDetails.html\',\''+curData[0]+'\',2)">修改价格</a></span>';
            }
        }else {

            if (curData[6]!=9&&curData[6]!=10&&curData[6]!=20){
                valall = '<span class="powerButton 109"><a style="opacity: 0.2">改价详情</a></span>';
            }else{
                valall = '<span class="powerButton 109"><a style="opacity: 0.2">修改价格</a></span>';
            }


        }

        inquiryStr+= '<td width="115" rowspan="'+curProLen+'">'+isUndefined(curData[2])+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+receivernames+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+paidtypeall[curData[4]]+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+sourceall[curData[8]]+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+(curData[5]).toFixed(2)+'</td>'+
            '<td width="70" rowspan="'+curProLen+'">'+state+'</td>'+
            '<td width="100" rowspan="'+curProLen+'">'+valall+'</td>';


        var showMoreHtml = '';
        if(curProLen>3){
            showMoreHtml = '<div class="list_more " onclick="showMore(this);"><a href="javascript:void(0);">查询了<span id="list_length">'+curProLen+'</span>件商品  <span id="operText">更多</span><i class="icon"></i></a></div>'
        }
        if(productData && productData.length>0){
            for(var j=0;j<productData.length;j++){
                var curPro = productData[j];
                if(j!=0){
                    inquiryStr = '';
                }

                var isHideClass = '';
                if(j>=3){
                    isHideClass = 'moretr hide';
                }

                productStr +='<tr class="'+isHideClass+'">'+
                    '<td width="75" rowspan="1"><img style="width:60px;height:60px;" src="' + imgSize(curPro.product_pic) + '"/></td>'+
                    '<td width="135" rowspan="1"><div>' + curPro.sku_code + '</div><div>' + curPro.product_name + '</div><div>' + curPro.color + '</div><div>' + curPro.sku_info + '</div></td>'+
                    '<td width="75" rowspan="1"><span>X</span>' + curPro.buyyer_count + '' + curPro.unit_name + '</td>'+  inquiryStr +
                    '</tr>';

            }


        }else{
            productStr +='<tr>'+
                '<td width="75" rowspan="1"></td>'+
                '<td width="135" rowspan="1"></td>'+
                '<td width="75" rowspan="1"></td>'+  inquiryStr +
                '</tr>';
        }

        outHtml+= '<div class="orer_item"><div class="list_box list_over">'+
            '<div class="title">'+
            '<span>订单号：'+isUndefined(curData[0])+'</span>'+
            '<span>下单时间：'+timeIsDefault(curData[1])+'</span>'+
            '</div>'+
            '<table style="width:100%;" class="table table-border table-bg table-sort list_box_table"><tbody>'+productStr+'</tbody></table></div>'+showMoreHtml+'</div>';
    }

    $('#orderList').empty().append(outHtml);
        //权限控制函数
        power()
}
function isUndefined(dt){
    var str = dt ? dt : '';
    return str;
}
function timeIsDefault(tm){
    var str = tm == '1000-01-01 00:00:00' ? '' : tm;
    return str;
}
//更多
function showMore(dom, length,status) {
    var curDom = $(dom);
    var curTr = curDom.parents('.orer_item').find('.moretr');
    if(curTr.eq(0).hasClass('hide')){
        curTr.removeClass('hide');
        curDom.find('#operText').html('收起');
    }else{
        curTr.addClass('hide');
        curDom.find('#operText').html('更多');
    }

}
function getList(){
    $("#area").val()
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.orderInter.order_queryOrder,
        //root.orderInter.order_queryOrder
        ///aorder/ordermanage/queryOrder
        cache: false,  //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            created_address_code: $("#area").val(),//地区
            parent_warehouse_id: $("#shippingWarehouse option:selected").val(),// 仓库id
            month_query:$("#timeSelect").val(),//选择支付时间段
            order_id:$("#orderCode").val(),// 订单编号
            search_param: $("#SKUCode").val(), //SKU码/code码
            order_status: $("#dealState").val(), // 交易状态
            paid_type: $("#payWay").val(), //支付方式
            created_at_begin: $("#timemin").val(), //下单开始时间
            created_at_end: $("#timemax").val(),//下单结束时间
            customer_name: $("#buyerName").val(), //买家名称
            receiver_name: $("#consignee").val(), //收货人姓名
            mobile: $("#phoneNum").val(), //收货人电话
            sales_manager_name: $("#saleManager").val(), //销售经理
            role_name: $("#orderPlacer").val(), //下单人
            receiver_province: $("#getArea").val(),// 一级收货地（收货区域）
            receiver_city: $("#getPlace").val(),// 二级收货地（收货位置）
            source: $("#source").val(),// 二级收货地（收货位置）
            register_phone: $("#register_phone").val(), // 绑定手机号
            page_num: 1, //当前页码
            page_size: 50,//每页显示条数
            query_source:'price_manage',
            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
        }),
        success: function (result) {
            sessionStorage.setItem("changetatus",'')
            orderList(result);
            var pageCounts=""
            if(result.data!=null){
                pageCounts=result.data.totalPage
            }else {
                pageCounts=0
            }
            $('.M-box3').pagination({
                pageCount: pageCounts,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        contentType: "application/json",
                        type: "POST",
                        url: root.orderInter.order_queryOrder,
                        cache: false,  //禁用缓存
                        dataType: "json",
                        data: JSON.stringify({
                            created_address_code: $("#area").val(),//地区
                            parent_warehouse_id: $("#shippingWarehouse option:selected").val(),// 仓库id
                            month_query:$("#timeSelect").val(),//选择支付时间段
                            order_id:$("#orderCode").val(),// 订单编号
                            search_param: $("#SKUCode").val(), //SKU码/code码
                            order_status: $("#dealState").val(), // 交易状态
                            paid_type: $("#payWay").val(), //支付方式
                            created_at_begin: $("#timemin").val(), //下单开始时间
                            created_at_end: $("#timemax").val(),//下单结束时间
                            customer_name: $("#buyerName").val(), //买家名称
                            receiver_name: $("#consignee").val(), //收货人姓名
                            mobile: $("#phoneNum").val(), //收货人电话
                            sales_manager_name: $("#saleManager").val(), //销售经理
                            role_name: $("#orderPlacer").val(), //下单人
                            receiver_province: $("#getArea").val(),// 一级收货地（收货区域）
                            receiver_city: $("#getPlace").val(),// 二级收货地（收货位置）
                            page_num: api.getCurrent(), //当前页码
                            page_size: 50,//每页显示条数
                            query_source:'price_manage',
                            companys_ids:sessionStorage.getItem("organizationWarehouse"),//公司对应的发货仓id
                            warehouse_ids:sessionStorage.getItem("regions"),//仓库权限串
                            belong_groupIds:sessionStorage.getItem("companys"),//销售归属权限串
                            sales_manager_ids:sessionStorage.getItem("personnels"),//销售经理权限串
                        }),
                        success: function (result) {
                            orderList(result);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
/*跳转订单详情*/
function orderInfo(title,url,data){
    sessionStorage.setItem("orderId",data);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
/*跳转订单改价*/
function orderchange(title,url,data,type){
    sessionStorage.setItem("orderId",data);
    sessionStorage.setItem("type",type);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
//弹框跳转
var changetatus= sessionStorage.getItem("changetatus")
if(changetatus==10){
    $("#dealState").val(changetatus)
    $("#timeSelect").val("")
    getList()
}
